home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1994 / MacHack 1994.toast / MacHack™ 1987-1994 / MacHack™ '92 / Hacks ’92 / WhereAmI / Sample.c next >
Encoding:
C/C++ Source or Header  |  1992-06-19  |  42.9 KB  |  1,440 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.c    -    C Source
  10. #
  11. #    Copyright © Apple Computer, Inc. 1989-1990
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89    MPW 3.1
  18. #                1.03                02/90    MPW 3.2
  19. #
  20. #    Components:
  21. #                Sample.c            Feb.  1, 1990
  22. #                Sample.r            Feb.  1, 1990
  23. #                Sample.h            Feb.  1, 1990
  24. #                Sample.make            Feb.  1, 1990
  25. #
  26. #    Sample is an example application that demonstrates how to
  27. #    initialize the commonly used toolbox managers, operate 
  28. #    successfully under MultiFinder, handle desk accessories, 
  29. #    and create, grow, and zoom windows.
  30. #
  31. #    It does not by any means demonstrate all the techniques 
  32. #    you need for a large application. In particular, Sample 
  33. #    does not cover exception handling, multiple windows/documents, 
  34. #    sophisticated memory management, printing, or undo. All of 
  35. #    these are vital parts of a normal full-sized application.
  36. #
  37. #    This application is an example of the form of a Macintosh 
  38. #    application; it is NOT a template. It is NOT intended to be 
  39. #    used as a foundation for the next world-class, best-selling, 
  40. #    600K application. A stick figure drawing of the human body may 
  41. #    be a good example of the form for a painting, but that does not 
  42. #    mean it should be used as the basis for the next Mona Lisa.
  43. #
  44. #    We recommend that you review this program or TESample before 
  45. #    beginning a new application.
  46. #
  47. ------------------------------------------------------------------------------*/
  48.  
  49.  
  50. /* Segmentation strategy:
  51.  
  52.    This program consists of three segments. Main contains most of the code,
  53.    including the MPW libraries, and the main program. Initialize contains
  54.    code that is only used once, during startup, and can be unloaded after the
  55.    program starts. %A5Init is automatically created by the Linker to initialize
  56.    globals for the MPW libraries and is unloaded right away. */
  57.  
  58.  
  59. /* SetPort strategy:
  60.  
  61.    Toolbox routines do not change the current port. In spite of this, in this
  62.    program we use a strategy of calling SetPort whenever we want to draw or
  63.    make calls which depend on the current port. This makes us less vulnerable
  64.    to bugs in other software which might alter the current port (such as the
  65.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  66.    Hopefully, this also makes the routines from this program more self-contained,
  67.    since they don't depend on the current port setting. */
  68.  
  69.  
  70. #include <Values.h>
  71. #include <Types.h>
  72. #include <Resources.h>
  73. #include <QuickDraw.h>
  74. #include <Fonts.h>
  75. #include <Events.h>
  76. #include <Windows.h>
  77. #include <Menus.h>
  78. #include <TextEdit.h>
  79. #include <Dialogs.h>
  80. #include <Desk.h>
  81. #include <ToolUtils.h>
  82. #include <Memory.h>
  83. #include <SegLoad.h>
  84. #include <Files.h>
  85. #include <OSUtils.h>
  86. #include <OSEvents.h>
  87. #include <DiskInit.h>
  88. #include <Packages.h>
  89. #include <Traps.h>
  90. #include "Sample.h"        /* bring in all the #defines for Sample */
  91.  
  92. #include <FixMath.h>
  93. #include <PLStringFuncs.h>
  94.  
  95. //
  96. //    My constants
  97. //
  98.  
  99. #define    kEarthsRadiusInMiles                (25000)
  100.  
  101. //
  102. //    My structures
  103. //
  104. typedef struct CityResourceFormat {
  105.     short            fRecordSize;
  106.     long            fLatitude, fLongitude;
  107.     long            fGMTOffset;
  108.     long            fUnknown1;
  109.     Str255            fCityName;
  110.     long            fUnknown2;
  111.     
  112. } CityResourceFormat, *CityResourceFormatPtr;
  113.  
  114. #define    kCityResourceType    'CTY#'
  115. #define    kCityResourceID        -4064
  116.  
  117. typedef struct CityRecord {
  118.     Str63            fCityName;
  119.     extended        fLatitude, fLongitude;
  120.     long            fGMTOffset;
  121.     
  122.     struct CityRecord*    fNext;
  123. } CityRecord, *CityRecordPtr;
  124.  
  125.  
  126. typedef struct PathItemRecord {
  127.     Str32        fStartingCity;
  128.     extended    fStartLatitude, fStartLongitude;
  129.     
  130.     Str32        fEndingCity;
  131.     extended    fEndLatitude, fEndLongitude;
  132.     
  133.     long        fTripDuration, fTripStartTime;
  134. } PathItemRecord;
  135.  
  136.  
  137.  
  138.  
  139. //
  140.  
  141. /* The "g" prefix is used to emphasize that a variable is global. */
  142.  
  143. /* GMac is used to hold the result of a SysEnvirons call. This makes
  144.    it convenient for any routine to check the environment. */
  145. SysEnvRec    gMac;                /* set up by Initialize */
  146.  
  147. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  148.    trap is available. If it is false, we know that we must call GetNextEvent. */
  149. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  150.  
  151. /* GInBackground is maintained by our osEvent handling routines. Any part of
  152.    the program can check it to find out if it is currently in the background. */
  153. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  154.  
  155.  
  156. CityRecordPtr                gCitiesRecordList = nil;
  157. CityRecordPtr                gNextCityToFlash = nil;
  158.  
  159. PicHandle                    gWorldMapPicH = nil;
  160. Point                        gWorldMapPicSize;
  161. Rect                        gWorldMapPicRect;
  162. Point                        gWorldMapCenter;
  163.  
  164. DialogPtr                    gOurWindow;
  165.  
  166. long                        gPathCount = 0;
  167. PathItemRecord                gPath[32];
  168.  
  169. long                        gPlaneXPosOverMap = 0, gPlaneYPosOverMap = 0;
  170.  
  171. Rect                        gRectToDrawWorldMapInto;
  172. Rect                        gDestinationListDisplayRect;
  173.  
  174. ControlHandle                gVerticalScrollBarControlH = nil;
  175. ControlHandle                gHorizontalScrollBarControlH = nil;
  176.  
  177. Boolean                        gPlaneIsVisible = false;
  178.  
  179. short                        gCurrentPath = 0;
  180.  
  181. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  182.    actual prototypes for parameter type checking. */
  183. void EventLoop( void );
  184. void DoEvent( EventRecord *event );
  185. void AdjustCursor( Point mouse, RgnHandle region );
  186. void GetGlobalMouse( Point *mouse );
  187. void DoUpdate( WindowPtr window );
  188. void DoActivate( WindowPtr window, Boolean becomingActive );
  189. void DoContentClick( WindowPtr window, EventRecord* event );
  190. void DrawWindow( WindowPtr window );
  191. void AdjustMenus( void );
  192. void DoMenuCommand( long menuResult );
  193. Boolean DoCloseWindow( WindowPtr window );
  194. void Terminate( void );
  195. void Initialize( void );
  196. Boolean GoGetRect( short rectID, Rect *theRect );
  197. void ForceEnvirons( void );
  198. Boolean IsAppWindow( WindowPtr window );
  199. Boolean IsDAWindow( WindowPtr window );
  200. Boolean TrapAvailable( short tNumber, TrapType tType );
  201. void AlertUser( void );
  202.  
  203. Boolean InitializeCitiesList();
  204. Boolean InitializeWorldMap();
  205. Boolean BlinkCity (WindowPtr window, CityRecordPtr cityP);
  206. Boolean BlinkAllCities (WindowPtr window);
  207.  
  208. long CalculateHowFarItIsToTheHorizonInMiles(long altitudeInMiles);
  209. Boolean UpdateOurPositionOnMap();
  210. Boolean GetOurXandYLocationOverMap(long *xPos, long *yPos);
  211.  
  212. Boolean MovePlaneToNextLogicalPositionAlongPath ();
  213.  
  214. CityRecordPtr FindCity(Str255 cityName);
  215. Boolean DrawOurPlaneAtXYPos(long xPos, long yPos);
  216. Boolean UndrawOurPlaneAtXYPos(long xPos, long yPos);
  217. Boolean DrawMapIntoWindow(WindowPtr window);
  218. pascal void DrawMapIntoWindowProc(DialogPtr dialogP, short item);
  219. pascal void DrawPathsIntoMapWindow(DialogPtr dialogP, short itemNumber);
  220. pascal void DrawOurPlaneIntoMapWindow(DialogPtr dialogP, short itemNumber);
  221. Boolean ReadPathListInFromResources ();
  222. void CreateTrafficMenu ();
  223. /* Define HiWrd and LoWrd macros for efficiency. */
  224. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  225. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  226.  
  227. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  228.    dependency on the ordering of fields within a Rect */
  229. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  230. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  231.  
  232.  
  233. extern void _DataInit();
  234.  
  235. /* This routine is part of the MPW runtime library. This external
  236.    reference to it is done so that we can unload its segment, %A5Init. */
  237.  
  238.  
  239. #pragma segment Main
  240. main()
  241. {
  242.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  243.     
  244.     /*    If you have stack requirements that differ from the default,
  245.         then you could use SetApplLimit to increase StackSpace at 
  246.         this point, before calling MaxApplZone. */
  247.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  248.  
  249.     Initialize();                    /* initialize the program */
  250.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  251.  
  252.     EventLoop();                    /* call the main event loop */
  253. }
  254.  
  255.  
  256. /*    Get events forever, and handle them by calling DoEvent.
  257.     Get the events by calling WaitNextEvent, if it's available, otherwise
  258.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  259.  
  260. #pragma segment Main
  261. void EventLoop()
  262. {
  263.     RgnHandle    cursorRgn;
  264.     Boolean        gotEvent;
  265.     EventRecord    event;
  266.     Point        mouse;
  267.  
  268.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  269.     do {
  270.         /* use WNE if it is available */
  271.         if ( gHasWaitNextEvent ) {
  272.             // GetGlobalMouse(&mouse);
  273.             // AdjustCursor(mouse, cursorRgn);
  274.             gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  275.         }
  276.         else {
  277.             SystemTask();
  278.             gotEvent = GetNextEvent(everyEvent, &event);
  279.         }
  280.         if ( gotEvent ) {
  281.             /* make sure we have the right cursor before handling the event */
  282.             // AdjustCursor(event.where, cursorRgn);
  283.             DoEvent(&event);
  284.         }
  285.         /*    If you are using modeless dialogs that have editText items,
  286.             you will want to call IsDialogEvent to give the caret a chance
  287.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  288.             for a non-NIL value before calling IsDialogEvent. */
  289.  
  290.         {    long oldX = gPlaneXPosOverMap; long oldY = gPlaneYPosOverMap;
  291.             if ( MovePlaneToNextLogicalPositionAlongPath () ) {
  292.                 UndrawOurPlaneAtXYPos(oldX, oldY);
  293.             };
  294.             DrawOurPlaneAtXYPos(gPlaneXPosOverMap, gPlaneYPosOverMap);
  295.         };
  296.         BlinkAllCities(gOurWindow);
  297.         
  298.         
  299.     } while ( true );    /* loop forever; we quit via ExitToShell */
  300. } /*EventLoop*/
  301.  
  302.  
  303. /* Do the right thing for an event. Determine what kind of event it is, and call
  304.  the appropriate routines. */
  305.  
  306. #pragma segment Main
  307. void DoEvent(event)
  308.     EventRecord    *event;
  309. {
  310.     short        part, err;
  311.     WindowPtr    window;
  312.     Boolean        hit;
  313.     char        key;
  314.     Point        aPoint;
  315.  
  316.     if (gNextCityToFlash) {
  317.         BlinkCity(gOurWindow, gNextCityToFlash);
  318.         gNextCityToFlash = gNextCityToFlash->fNext;
  319.     } else {
  320.         gNextCityToFlash = gCitiesRecordList;
  321.     };            
  322.  
  323.     switch ( event->what ) {
  324.         case nullEvent:
  325.             if (gNextCityToFlash) {
  326.                 BlinkCity(gOurWindow, gNextCityToFlash);
  327.                 gNextCityToFlash = gNextCityToFlash->fNext;
  328.             } else {
  329.                 gNextCityToFlash = gCitiesRecordList;
  330.             };
  331.             break;
  332.             
  333.         case mouseDown:
  334.             part = FindWindow(event->where, &window);
  335.             switch ( part ) {
  336.                 case inMenuBar:                /* process a mouse menu command (if any) */
  337.                     AdjustMenus();
  338.                     DoMenuCommand(MenuSelect(event->where));
  339.                     break;
  340.                 case inSysWindow:            /* let the system handle the mouseDown */
  341.                     SystemClick(event, window);
  342.                     break;
  343.                 case inContent:
  344.                     if ( window != FrontWindow() ) {
  345.                         SelectWindow(window);
  346.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  347.                     } else {
  348.                         DoContentClick(window, event);
  349.                     };
  350.                     break;
  351.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  352.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  353.                     break;
  354.                 case inGrow:
  355.                     break;
  356.                 case inZoomIn:
  357.                 case inZoomOut:
  358.                     hit = TrackBox(window, event->where, part);
  359.                     if ( hit ) {
  360.                         SetPort(window);                /* the window must be the current port... */
  361.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  362.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  363.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  364.                     }
  365.                     break;
  366.             }
  367.             break;
  368.             
  369.         case keyDown:
  370.         case autoKey:                        /* check for menukey equivalents */
  371.             key = event->message & charCodeMask;
  372.             if ( event->modifiers & cmdKey )            /* Command key down */
  373.                 if ( event->what == keyDown ) {
  374.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  375.                     DoMenuCommand(MenuKey(key));
  376.                 }
  377.             break;
  378.             
  379.         case activateEvt:
  380.         
  381.             // DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  382.             SelectWindow ((WindowPtr) event->message);
  383.             
  384.             break;
  385.             
  386.         case updateEvt:     {
  387.             DialogPtr dialogP = (DialogPtr) event->message;
  388.             
  389.             BeginUpdate(dialogP);
  390.             UpdtDialog(dialogP, dialogP->visRgn);
  391.  
  392.             // DrawMapIntoWindowProc(dialogP, 1);
  393.             EndUpdate(dialogP);
  394.             
  395.             // DoUpdate((WindowPtr) event->message);
  396.             break;
  397.         };
  398.             
  399.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  400.             to a diskEvt, so that the user can format a floppy. */
  401.         case diskEvt:
  402.             if ( HiWord(event->message) != noErr ) {
  403.                 SetPt(&aPoint, kDILeft, kDITop);
  404.                 err = DIBadMount(aPoint, event->message);
  405.             }
  406.             break;
  407.             
  408.         case kOSEvent:
  409.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  410.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  411.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  412.                     gInBackground = (event->message & kResumeMask) == 0;
  413.                     DoActivate(FrontWindow(), !gInBackground);
  414.                     break;
  415.             }
  416.             break;
  417.     }
  418. } /*DoEvent*/
  419.  
  420.  
  421. /*    Change the cursor's shape, depending on its position. This also calculates the region
  422.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  423.     that region, an event would be generated, causing this routine to be called,
  424.     allowing us to change the region to the region the mouse is currently in. If
  425.     there is more to the event than just “the mouse moved”, we get called before the
  426.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  427.     this is called again before we     fall back into WNE. */
  428.  
  429. #pragma segment Main
  430. void AdjustCursor(mouse,region)
  431.     Point        mouse;
  432.     RgnHandle    region;
  433. {
  434.     WindowPtr    window;
  435.     RgnHandle    arrowRgn;
  436.     RgnHandle    plusRgn;
  437.     Rect        globalPortRect;
  438.  
  439.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  440.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  441.         /* calculate regions for different cursor shapes */
  442.         arrowRgn = NewRgn();
  443.         plusRgn = NewRgn();
  444.  
  445.         /* start with a big, big rectangular region */
  446.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  447.  
  448.         /* calculate plusRgn */
  449.         if ( IsAppWindow(window) ) {
  450.             SetPort(window);    /* make a global version of the viewRect */
  451.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  452.             globalPortRect = window->portRect;
  453.             RectRgn(plusRgn, &globalPortRect);
  454.             SectRgn(plusRgn, window->visRgn, plusRgn);
  455.             SetOrigin(0, 0);
  456.         }
  457.  
  458.         /* subtract other regions from arrowRgn */
  459.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  460.  
  461.         /* change the cursor and the region parameter */
  462.         if ( PtInRgn(mouse, plusRgn) ) {
  463.             SetCursor(*GetCursor(plusCursor));
  464.             CopyRgn(plusRgn, region);
  465.         } else {
  466.             SetCursor(&qd.arrow);
  467.             CopyRgn(arrowRgn, region);
  468.         }
  469.  
  470.         /* get rid of our local regions */
  471.         DisposeRgn(arrowRgn);
  472.         DisposeRgn(plusRgn);
  473.     }
  474. } /*AdjustCursor*/
  475.  
  476.  
  477. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  478.     it will return either a pending event or a null event. In either case,
  479.     the where field of the event record will contain the current position
  480.     of the mouse in global coordinates and the modifiers field will reflect
  481.     the current state of the modifiers. Another way to get the global
  482.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  483.     being sure that thePort is set to a valid port. */
  484.  
  485. #pragma segment Main
  486. void GetGlobalMouse(mouse)
  487.     Point    *mouse;
  488. {
  489.     EventRecord    event;
  490.     
  491.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  492.     *mouse = event.where;                /* just the mouse position */
  493. } /*GetGlobalMouse*/
  494.  
  495.  
  496. /*    This is called when an update event is received for a window.
  497.     It calls DrawWindow to draw the contents of an application window.
  498.     As an effeciency measure that does not have to be followed, it
  499.     calls the drawing routine only if the visRgn is non-empty. This
  500.     will handle situations where calculations for drawing or drawing
  501.     itself is very time-consuming. */
  502.  
  503. #pragma segment Main
  504. void DoUpdate(window)
  505.     WindowPtr    window;
  506. {
  507.     if ( IsAppWindow(window) ) {
  508.         BeginUpdate(window);                /* this sets up the visRgn */
  509.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  510.             // DrawWindow(window);
  511.         EndUpdate(window);
  512.     }
  513. } /*DoUpdate*/
  514.  
  515.  
  516. /*    This is called when a window is activated or deactivated.
  517.     In Sample, the Window Manager's handling of activate and
  518.     deactivate events is sufficient. Other applications may have
  519.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  520.  
  521. #pragma segment Main
  522. void DoActivate(window, becomingActive)
  523.     WindowPtr    window;
  524.     Boolean        becomingActive;
  525. {
  526.     if ( IsAppWindow(window) ) {
  527.         if ( becomingActive ) {
  528.             /* do whatever you need to at activation */ ;
  529.         } else {
  530.             /* do whatever you need to at deactivation */ ;
  531.         };
  532.     }
  533. } /*DoActivate*/
  534.  
  535.  
  536. /*    This is called when a mouse-down event occurs in the content of a window.
  537.     Other applications might want to call FindControl, TEClick, etc., to
  538.     further process the click. */
  539.  
  540. pascal void MyScrollAction (ControlHandle controlH, short partCode) {
  541.     long currentValue = GetCtlValue(controlH);
  542.     switch (partCode) {
  543.         case inUpButton: currentValue -= 8; break;
  544.         case inDownButton: currentValue += 8; break;
  545.         case inPageUp: currentValue -= 32; break;
  546.         case inPageDown: currentValue += 32; break;
  547.         case inThumb: break;
  548.     };
  549.     SetCtlValue(controlH, currentValue);
  550.     DrawMapIntoWindowProc(gOurWindow, 1);
  551. };
  552.  
  553. #pragma segment Main
  554. void DoContentClick(WindowPtr window, EventRecord *event) {
  555.     ControlHandle controlH;
  556.     short whichPart;
  557.     
  558.     SetPort(window);
  559.     GlobalToLocal(&event->where);
  560.     
  561.     whichPart = FindControl(event->where, window, &controlH);
  562.     
  563.     if (whichPart) {
  564.         whichPart = TrackControl(controlH, event->where, (ProcPtr) &MyScrollAction);
  565.         
  566.         if ((controlH == gVerticalScrollBarControlH) ||
  567.             (controlH == gHorizontalScrollBarControlH)) {
  568.                 InvalRect(&gRectToDrawWorldMapInto);
  569.         };
  570.     };
  571.     
  572. } /*DoContentClick*/
  573.  
  574.  
  575. #define kScaleFactor 1
  576.  
  577. Boolean GetXandYPositionOverMap(extended latitude, extended longitude, long* xPos, long* yPos) {
  578.     int        picSizeY = (gWorldMapPicSize.v) >> 1;
  579.     int        picSizeX = gWorldMapPicSize.h >> 1;    
  580.  
  581.     long leftEdge = GetCtlValue(gHorizontalScrollBarControlH);
  582.     long topEdge = GetCtlValue(gVerticalScrollBarControlH);                
  583.  
  584.     *yPos = -topEdge + (int) ((-1 * latitude * picSizeY) + picSizeY);
  585.     *xPos = -leftEdge + (int) ((((longitude / 2) * picSizeX )) + picSizeX);
  586.         
  587.     return true;
  588. };
  589.  
  590.  
  591.  
  592. CityRecordPtr FindCity(Str255 cityName) {
  593.     CityRecordPtr    cityP = gCitiesRecordList;
  594.     
  595.     while (cityP) {
  596.         if (IUEqualString(cityP->fCityName, cityName) == 0) {
  597.             return cityP;
  598.         };
  599.         cityP = cityP->fNext;
  600.     };
  601.     
  602.     DebugStr (cityName);
  603.     return nil;
  604. };
  605.  
  606.  
  607.  
  608. /* Draw the contents of the application window. We do some drawing in color, using
  609.    Classic QuickDraw's color capabilities. This will be black and white on old
  610.    machines, but color on color machines. At this point, the window’s visRgn
  611.    is set to allow drawing only where it needs to be done. */
  612.  
  613.  
  614. #pragma segment Main
  615.  
  616. pascal void DrawMapIntoWindowProc(DialogPtr dialogP, short itemNumber) {
  617. #pragma usused(itemNumber);
  618.     long leftEdge, topEdge;
  619.     RgnHandle    savedClip = NewRgn();
  620.     RgnHandle    newClipRgn = NewRgn();
  621.     RgnHandle    rectClipRgn = NewRgn();
  622.         
  623.     SetPort(dialogP);    
  624.         
  625.     GetClip(savedClip);
  626.     RectRgn(rectClipRgn, &gRectToDrawWorldMapInto);
  627.     SectRgn(savedClip, rectClipRgn, newClipRgn);
  628.     SetClip(newClipRgn);
  629.  
  630.     //    Figure out where to offset the origin so the point in
  631.     //    gOurLocation is at the center of the map.
  632.  
  633.     leftEdge = GetCtlValue(gHorizontalScrollBarControlH);
  634.     topEdge = GetCtlValue(gVerticalScrollBarControlH);                
  635.     
  636.     UndrawOurPlaneAtXYPos(gPlaneXPosOverMap, gPlaneYPosOverMap);
  637.     
  638.     if (true) {    
  639.         Rect    rectToDrawIn;
  640.  
  641.         rectToDrawIn = (**gWorldMapPicH).picFrame;
  642.         
  643.         rectToDrawIn.bottom = (rectToDrawIn.bottom - rectToDrawIn.top);
  644.         rectToDrawIn.right =  (rectToDrawIn.right - rectToDrawIn.left);
  645.         rectToDrawIn.top = 0;
  646.         rectToDrawIn.left = 0;
  647.         
  648.         OffsetRect (&rectToDrawIn, -leftEdge, -topEdge);
  649.         DrawPicture (gWorldMapPicH, &rectToDrawIn);
  650.         
  651.         // 
  652.     };
  653.     
  654.     DrawPathsIntoMapWindow(dialogP, itemNumber);
  655.     
  656.     DrawOurPlaneIntoMapWindow(dialogP, itemNumber);
  657.     
  658.     SetClip(savedClip);
  659.  
  660.     DisposeRgn(savedClip);
  661.     DisposeRgn(newClipRgn);
  662.     DisposeRgn(rectClipRgn);
  663. };
  664.  
  665.  
  666. pascal void DrawPathsIntoMapWindow(DialogPtr dialogP, short itemNumber) {
  667.     
  668.     int index;
  669.     
  670.     PenSize(2,2);
  671.     
  672.     for (index = 0; index < gPathCount; ++index) {
  673.         long startX, startY, endX, endY;
  674.  
  675.         if (index == gCurrentPath) {
  676.             PenPat(&qd.gray);
  677.         } else {
  678.             PenPat(&qd.dkGray);
  679.         };
  680.         
  681.         GetXandYPositionOverMap(gPath[index].fStartLatitude, 
  682.                                 gPath[index].fStartLongitude,
  683.                                 &startX, &startY);
  684.         GetXandYPositionOverMap(gPath[index].fEndLatitude, 
  685.                                 gPath[index].fEndLongitude,
  686.                                 &endX, &endY);
  687.         MoveTo(startX, startY);
  688.         LineTo(endX, endY);
  689.     };
  690.     PenNormal();
  691.     
  692. }
  693.  
  694.  
  695.  
  696. pascal void DrawOurPlaneIntoMapWindow(DialogPtr dialogP, short itemNumber) {
  697.      
  698.     DrawOurPlaneAtXYPos    (gPlaneXPosOverMap, gPlaneYPosOverMap);
  699.     
  700.     return;
  701. };
  702.  
  703. pascal void DrawDataDisplayIntoWindowProc(DialogPtr dialogP, short itemNumber) {
  704.     short itemType;
  705.     Handle item;
  706.     Rect r = gDestinationListDisplayRect;
  707.     short y, index;
  708.         
  709.     TextFont (1);
  710.     TextSize(10);
  711.             
  712.     y = r.top + 4 + 10;
  713.     for (index = 0; index < gPathCount; ++index) {
  714.         Str255 s;
  715.             
  716.         MoveTo (r.left + 4, y);
  717.         DrawString (&gPath[index].fStartingCity);
  718.         
  719.         if (gPath[index].fTripStartTime > 0) {
  720.             IUTimeString(gPath[index].fTripStartTime, false, &s);
  721.             MoveTo (r.right - 4 - StringWidth(s), y);
  722.             DrawString (s);
  723.         };
  724.         
  725.         y += 12;
  726.  
  727.         MoveTo (r.left + 4, y);
  728.         DrawString (gPath[index].fEndingCity);
  729.         if (gPath[index].fTripStartTime > 0) {
  730.             IUTimeString(gPath[index].fTripStartTime + gPath[index].fTripDuration,
  731.                                 false, &s);
  732.             MoveTo (r.right - 4 - StringWidth(s), y);
  733.             DrawString (s);
  734.         };
  735.             
  736.         PenPat (&qd.gray);
  737.         MoveTo (r.left + 16, y + 4);
  738.         LineTo (r.right - 16, y + 4);
  739.         
  740.         y += 16;
  741.     };
  742.  
  743. };
  744.  
  745. Boolean IsPointInVisibleAreaOfMap (long x, long y) {
  746.     Point p; p.h = x; p.v = y;
  747.     return PtInRect(p, &gRectToDrawWorldMapInto);
  748. };
  749.  
  750.  
  751. Boolean DrawOurPlaneAtXYPos(long xPos, long yPos) {
  752.     Rect    r, garbageRect;
  753.     
  754.     r.top = r.bottom = yPos;
  755.     r.left = r.right = xPos;
  756.         
  757.     InsetRect (&r, -3, -3);
  758.  
  759.     if ((gPlaneIsVisible == true) || (IsPointInVisibleAreaOfMap(xPos, yPos))) {
  760.         InvertOval (&r);
  761.         gPlaneIsVisible = !gPlaneIsVisible;
  762.     };
  763.     
  764.     return true;
  765. };
  766.  
  767. Boolean UndrawOurPlaneAtXYPos(long xPos, long yPos) {
  768.     while (gPlaneIsVisible)
  769.         DrawOurPlaneAtXYPos(xPos, yPos);
  770.     return true;
  771. };
  772.  
  773. Boolean MovePlaneToNextLogicalPositionAlongPath () {
  774.     extended latitude, longitude;
  775.     unsigned long now;
  776.     long index;
  777.     long xPos, yPos;
  778.     
  779.     GetDateTime(&now);
  780.     latitude = gPath[0].fStartLatitude;
  781.     longitude = gPath[0].fStartLongitude;
  782.  
  783.         if  (true) { 
  784.             if (now - gPath[gCurrentPath].fTripStartTime <= gPath[gCurrentPath].fTripDuration) {
  785.                 long    timeIntoPath = now - gPath[gCurrentPath].fTripStartTime;
  786.                 long    pathDuration = gPath[gCurrentPath].fTripDuration;
  787.                 float    percentAlongPath = ((float) timeIntoPath) / pathDuration;
  788.                 
  789.                 latitude = (gPath[gCurrentPath].fEndLatitude - gPath[gCurrentPath].fStartLatitude) *
  790.                             (percentAlongPath) + gPath[gCurrentPath].fStartLatitude;
  791.                 longitude = (gPath[gCurrentPath].fEndLongitude - gPath[gCurrentPath].fStartLongitude) *
  792.                             (percentAlongPath) + gPath[gCurrentPath].fStartLongitude;
  793.             } else {
  794.                 latitude = gPath[gCurrentPath].fEndLatitude;
  795.                 longitude = gPath[gCurrentPath].fEndLongitude;
  796.                 gCurrentPath++;
  797.             };
  798.         };
  799.     
  800.     GetXandYPositionOverMap (latitude, longitude, &xPos, &yPos);
  801.     
  802.     if ((xPos != gPlaneXPosOverMap) || (yPos != gPlaneYPosOverMap)) {
  803.         UndrawOurPlaneAtXYPos(gPlaneXPosOverMap, gPlaneYPosOverMap);
  804.         gPlaneXPosOverMap = xPos;
  805.         gPlaneYPosOverMap = yPos;
  806.         return true;
  807.     };
  808.     return false;
  809. };
  810.  
  811.  
  812. /*    Enable and disable menus based on the current state.
  813.     The user can only select enabled menu items. We set up all the menu items
  814.     before calling MenuSelect or MenuKey, since these are the only times that
  815.     a menu item can be selected. Note that MenuSelect is also the only time
  816.     the user will see menu items. This approach to deciding what enable/
  817.     disable state a menu item has the advantage of concentrating all
  818.     the decision-making in one routine, as opposed to being spread throughout
  819.     the application. Other application designs may take a different approach
  820.     that is just as valid. */
  821.  
  822. #pragma segment Main
  823. void AdjustMenus()
  824. {
  825.     WindowPtr    window;
  826.     MenuHandle    menu;
  827.  
  828.     window = FrontWindow();
  829.  
  830.     menu = GetMHandle(mFile);
  831.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  832.         EnableItem(menu, iClose);
  833.     else
  834.         DisableItem(menu, iClose);    /* but not our traffic light window */
  835.  
  836.     menu = GetMHandle(mEdit);
  837.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  838.         EnableItem(menu, iUndo);
  839.         EnableItem(menu, iCut);
  840.         EnableItem(menu, iCopy);
  841.         EnableItem(menu, iClear);
  842.         EnableItem(menu, iPaste);
  843.     } else {                        /* …but we don’t use it */
  844.         DisableItem(menu, iUndo);
  845.         DisableItem(menu, iCut);
  846.         DisableItem(menu, iCopy);
  847.         DisableItem(menu, iClear);
  848.         DisableItem(menu, iPaste);
  849.     }
  850.  
  851. } /*AdjustMenus*/
  852.  
  853.  
  854. /*    This is called when an item is chosen from the menu bar (after calling
  855.     MenuSelect or MenuKey). It performs the right operation for each command.
  856.     It is good to have both the result of MenuSelect and MenuKey go to
  857.     one routine like this to keep everything organized. */
  858.  
  859. #pragma segment Main
  860. void DoMenuCommand(menuResult)
  861.     long        menuResult;
  862. {
  863.     short        menuID;                /* the resource ID of the selected menu */
  864.     short        menuItem;            /* the item number of the selected menu */
  865.     short        itemHit;
  866.     Str255        daName;
  867.     short        daRefNum;
  868.     Boolean        handledByDA;
  869.  
  870.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  871.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  872.     switch ( menuID ) {
  873.         case mApple:
  874.             switch ( menuItem ) {
  875.                 case iAbout:        /* bring up alert for About */
  876.                     itemHit = Alert(rAboutAlert, nil);
  877.                     break;
  878.                 default:            /* all non-About items in this menu are DAs */
  879.                     /* type Str255 is an array in MPW 3 */
  880.                     GetItem(GetMHandle(mApple), menuItem, daName);
  881.                     daRefNum = OpenDeskAcc(daName);
  882.                     break;
  883.             }
  884.             break;
  885.         case mFile:
  886.             switch ( menuItem ) {
  887.                 case iClose:
  888.                     DoCloseWindow(FrontWindow());
  889.                     break;
  890.                 case iQuit:
  891.                     Terminate();
  892.                     break;
  893.             }
  894.             break;
  895.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  896.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  897.             break;
  898.         
  899.         case mLight: 
  900.         {    unsigned long now; GetDateTime(&now);
  901.             DebugStr ("\pmLight menu");
  902.             
  903.             gCurrentPath = menuItem-1;
  904.             gPath[gCurrentPath].fTripStartTime = now;
  905.             break ;
  906.         };
  907.  
  908.     }
  909.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  910. } /*DoMenuCommand*/
  911.  
  912.  
  913. /* Change the setting of the light. */
  914.  
  915. /* Close a window. This handles desk accessory and application windows. */
  916.  
  917. /*    1.01 - At this point, if there was a document associated with a
  918.     window, you could do any document saving processing if it is 'dirty'.
  919.     DoCloseWindow would return true if the window actually closed, i.e.,
  920.     the user didn’t cancel from a save dialog. This result is handy when
  921.     the user quits an application, but then cancels the save of a document
  922.     associated with a window. */
  923.  
  924. #pragma segment Main
  925. Boolean DoCloseWindow(window)
  926.     WindowPtr    window;
  927. {
  928.     if ( IsDAWindow(window) )
  929.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  930.     else if ( IsAppWindow(window) )
  931.         DisposeDialog(window);
  932.     return true;
  933. } /*DoCloseWindow*/
  934.  
  935.  
  936. /**************************************************************************************
  937. *** 1.01 DoCloseBehind(window) was removed ***
  938.  
  939.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  940.     and not having to worry about updating the windows, but it suffered
  941.     from a fatal flaw. If a desk accessory owned two windows, it would
  942.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  943.     got around to calling DoCloseWindow for that other window that was already
  944.     closed, things would go very poorly. Another option would be to have a
  945.     procedure, GetRearWindow, that would go through the window list and return
  946.     the last window. Instead, we decided to present the standard approach
  947.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  948.     has a potential benefit in that the window whose document needs to be saved
  949.     may be visible since it is the front window, therefore decreasing the
  950.     chance of user confusion. For aesthetic reasons, the windows in the
  951.     application should be checked for updates periodically and have the
  952.     updates serviced.
  953. **************************************************************************************/
  954.  
  955.  
  956. /* Clean up the application and exit. We close all of the windows so that
  957.  they can update their documents, if any. */
  958.  
  959. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  960.     shell, but will return instead. */
  961.  
  962. #pragma segment Main
  963. void Terminate()
  964. {
  965.     WindowPtr    aWindow;
  966.     Boolean        closed;
  967.     
  968.     closed = true;
  969.     do {
  970.         aWindow = FrontWindow();                /* get the current front window */
  971.         if (aWindow != nil)
  972.             closed = DoCloseWindow(aWindow);    /* close this window */    
  973.     }
  974.     while (closed && (aWindow != nil));
  975.     if (closed)
  976.         ExitToShell();                            /* exit if no cancellation */
  977. } /*Terminate*/
  978.  
  979.  
  980. /*    Set up the whole world, including global variables, Toolbox managers,
  981.     and menus. We also create our one application window at this time.
  982.     Since window storage is non-relocateable, how and when to allocate space
  983.     for windows is very important so that heap fragmentation does not occur.
  984.     Because Sample has only one window and it is only disposed when the application
  985.     quits, we will allocate its space here, before anything that might be a locked
  986.     relocatable object gets into the heap. This way, we can force the storage to be
  987.     in the lowest memory available in the heap. Window storage can differ widely
  988.     amongst applications depending on how many windows are created and disposed. */
  989.  
  990. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  991.     this module. If an error is detected, instead of merely doing an ExitToShell,
  992.     which leaves the user without much to go on, we call AlertUser, which puts
  993.     up a simple alert that just says an error occurred and then calls ExitToShell.
  994.     Since there is no other cleanup needed at this point if an error is detected,
  995.     this form of error- handling is acceptable. If more sophisticated error recovery
  996.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  997.  
  998. #pragma segment Initialize
  999. void Initialize()
  1000. {
  1001.     Handle        menuBar;
  1002.     long        total, contig;
  1003.     EventRecord event;
  1004.     short        count;
  1005.  
  1006.     gInBackground = false;
  1007.  
  1008.     InitGraf((Ptr) &qd.thePort);
  1009.     InitFonts();
  1010.     InitWindows();
  1011.     InitMenus();
  1012.     TEInit();
  1013.     InitDialogs(nil);
  1014.     InitCursor();
  1015.     
  1016.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  1017.          if you are using it. */
  1018.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  1019.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  1020.         of checking for port availability themselves. */
  1021.     
  1022.     /*    This next bit of code is necessary to allow the default button of our
  1023.         alert be outlined.
  1024.         1.02 - Changed to call EventAvail so that we don't lose some important
  1025.         events. */
  1026.      
  1027.     for (count = 1; count <= 3; count++)
  1028.         EventAvail(everyEvent, &event);
  1029.     
  1030.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  1031.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  1032.         call to SysEnvirons by calling it after initializing AppleTalk. */
  1033.      
  1034.     SysEnvirons(kSysEnvironsVersion, &gMac);
  1035.     
  1036.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  1037.     
  1038.     if (gMac.machineType < 0) AlertUser();
  1039.     
  1040.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  1041.         in TrapAvailable if a tool trap value is out of range. */
  1042.         
  1043.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  1044.  
  1045.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  1046.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  1047.         MultiFinder we needed. This did not work well because it assumed too much about
  1048.         the relationship between what we asked MultiFinder for and what we would actually
  1049.         get back, as well as how to measure it. Instead, we will use an alternate
  1050.         method comprised of two steps. */
  1051.      
  1052.     /*    It is better to first check the size of the application heap against a value
  1053.         that you have determined is the smallest heap the application can reasonably
  1054.         work in. This number should be derived by examining the size of the heap that
  1055.         is actually provided by MultiFinder when the minimum size requested is used.
  1056.         The derivation of the minimum size requested from MultiFinder is described
  1057.         in Sample.h. The check should be made because the preferred size can end up
  1058.         being set smaller than the minimum size by the user. This extra check acts to
  1059.         insure that your application is starting from a solid memory foundation. */
  1060.      
  1061.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  1062.     
  1063.     /*    Next, make sure that enough memory is free for your application to run. It
  1064.         is possible for a situation to arise where the heap may have been of required
  1065.         size, but a large scrap was loaded which left too little memory. To check for
  1066.         this, call PurgeSpace and compare the result with a value that you have determined
  1067.         is the minimum amount of free memory your application needs at initialization.
  1068.         This number can be derived several different ways. One way that is fairly
  1069.         straightforward is to run the application in the minimum size configuration
  1070.         as described previously. Call PurgeSpace at initialization and examine the value
  1071.         returned. However, you should make sure that this result is not being modified
  1072.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  1073.         PurgeSpace. Make sure to remove that call before shipping, though. */
  1074.     
  1075.     /* ZeroScrap(); */
  1076.  
  1077.     PurgeSpace(&total, &contig);
  1078.     if (total < kMinSpace) AlertUser();
  1079.  
  1080.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  1081.         to check memory is that we can now give the user an alert to tell him/her what
  1082.         happened. Although it is possible that the memory situation could be worsened by
  1083.         displaying an alert, MultiFinder would gracefully exit the application with
  1084.         an informative alert if memory became critical. Here we are acting more
  1085.         in a preventative manner to avoid future disaster from low-memory problems. */
  1086.  
  1087.  
  1088.     InitializeWorldMap();
  1089.  
  1090.     gOurWindow = GetNewDialog(rWindow, nil, (WindowPtr) -1);
  1091.  
  1092.     {    short itemType;
  1093.         Handle item;
  1094.         Rect r;
  1095.         
  1096.         GetDItem(gOurWindow, 1, &itemType, &item, &gRectToDrawWorldMapInto);
  1097.         SetDItem(gOurWindow, 1, itemType, (Handle) &DrawMapIntoWindowProc, &gRectToDrawWorldMapInto);
  1098.         
  1099.         GetDItem(gOurWindow, 2, &itemType, &item, &gDestinationListDisplayRect);
  1100.         SetDItem(gOurWindow, 2, itemType, (Handle) &DrawDataDisplayIntoWindowProc, &gDestinationListDisplayRect);
  1101.  
  1102.  
  1103.         GetDItem(gOurWindow, 4, &itemType, &item, &r);
  1104.         gVerticalScrollBarControlH = (ControlHandle) item;
  1105.         
  1106.         GetDItem(gOurWindow, 3, &itemType, &item, &r);
  1107.         gHorizontalScrollBarControlH = (ControlHandle) item;
  1108.     };
  1109.     
  1110.     // SizeWindow(window, gWorldMapPicSize.h, gWorldMapPicSize.v, true);
  1111.     SetCtlMax(gVerticalScrollBarControlH, gWorldMapPicSize.v - (gRectToDrawWorldMapInto.bottom - gRectToDrawWorldMapInto.top));
  1112.     SetCtlMax(gHorizontalScrollBarControlH, gWorldMapPicSize.h - (gRectToDrawWorldMapInto.right - gRectToDrawWorldMapInto.left));
  1113.  
  1114.     SetCtlValue(gVerticalScrollBarControlH, 10);
  1115.     SetCtlValue(gHorizontalScrollBarControlH, 10);
  1116.  
  1117.     ShowWindow(gOurWindow);
  1118.     
  1119.     
  1120.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  1121.     if ( menuBar == nil ) AlertUser();
  1122.     SetMenuBar(menuBar);                    /* install menus */
  1123.     DisposHandle(menuBar);
  1124.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  1125.     DrawMenuBar();
  1126.             
  1127.         
  1128.     InitializeCitiesList();
  1129.     
  1130.  
  1131. } /*Initialize*/
  1132.  
  1133.  
  1134. /*    This utility loads the global rectangles that are used by the window
  1135.     drawing routines. It shows how the resource manager can be used to hold
  1136.     values in a convenient manner. These values are then easily altered without
  1137.     having to re-compile the source code. In this particular case, we know
  1138.     that this routine is being called at initialization time. Therefore,
  1139.     if a failure occurs here, we will assume that the application is in such
  1140.     bad shape that we should just exit. Your error handling may differ, but
  1141.     the check should still be made. */
  1142.     
  1143. #pragma segment Initialize
  1144. Boolean GoGetRect(rectID,theRect)
  1145.     short    rectID;
  1146.     Rect    *theRect;
  1147. {
  1148.     Handle        resource;
  1149.     
  1150.     resource = GetResource('RECT', rectID);
  1151.     if ( resource != nil ) {
  1152.         *theRect = **((Rect**) resource);
  1153.         return true;
  1154.     }
  1155.     else
  1156.         return false;
  1157. } /* GoGetRect */
  1158.  
  1159.  
  1160. /*    Check to see if a window belongs to the application. If the window pointer
  1161.     passed was NIL, then it could not be an application window. WindowKinds
  1162.     that are negative belong to the system and windowKinds less than userKind
  1163.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1164.     mean it is a dialog.
  1165.     1.02 - In order to reduce the chance of accidentally treating some window
  1166.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  1167.     is userKind. If you add different kinds of windows to Sample you'll need
  1168.     to change how this all works. */
  1169.  
  1170. #pragma segment Main
  1171. Boolean IsAppWindow(window)
  1172.     WindowPtr    window;
  1173. {
  1174.     short        windowKind;
  1175.  
  1176.     if ( window == nil )
  1177.         return false;
  1178.     else {    /* application windows have windowKinds = userKind (8) */
  1179.         return window == gOurWindow;
  1180.     }
  1181. } /*IsAppWindow*/
  1182.  
  1183.  
  1184. /* Check to see if a window belongs to a desk accessory. */
  1185.  
  1186. #pragma segment Main
  1187. Boolean IsDAWindow(window)
  1188.     WindowPtr    window;
  1189. {
  1190.     if ( window == nil )
  1191.         return false;
  1192.     else    /* DA windows have negative windowKinds */
  1193.         return ((WindowPeek) window)->windowKind < 0;
  1194. } /*IsDAWindow*/
  1195.  
  1196.  
  1197. /*    Check to see if a given trap is implemented. This is only used by the
  1198.     Initialize routine in this program, so we put it in the Initialize segment.
  1199.     The recommended approach to see if a trap is implemented is to see if
  1200.     the address of the trap routine is the same as the address of the
  1201.     Unimplemented trap. */
  1202. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  1203.     if a ToolTrap is out of range of a pre-MacII ROM. */
  1204.  
  1205. #pragma segment Initialize
  1206. Boolean TrapAvailable(tNumber,tType)
  1207.     short        tNumber;
  1208.     TrapType    tType;
  1209. {
  1210.     if ( ( tType == ToolTrap ) &&
  1211.         ( gMac.machineType > envMachUnknown ) &&
  1212.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  1213.         tNumber = tNumber & 0x03FF;
  1214.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  1215.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  1216.     }
  1217.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  1218. } /*TrapAvailable*/
  1219.  
  1220.  
  1221. /*    Display an alert that tells the user an error occurred, then exit the program.
  1222.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1223.     the continuation of the application. Errors that do not require the termination
  1224.     of the application should be handled in a different manner. Error checking and
  1225.     reporting has a place even in the simplest application. The error number is used
  1226.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1227.  
  1228. #pragma segment Main
  1229. void AlertUser()
  1230. {
  1231.     short        itemHit;
  1232.  
  1233.     SetCursor(&qd.arrow);
  1234.     itemHit = Alert(rUserAlert, nil);
  1235.     ExitToShell();
  1236. } /* AlertUser */
  1237.  
  1238. Boolean AddCityToPath(CityRecordPtr startCityP, CityRecordPtr endCityP, long start, long end) {
  1239.     if ((startCityP) && (endCityP)) {
  1240.         gPath[gPathCount].fStartLatitude = startCityP->fLatitude;
  1241.         gPath[gPathCount].fStartLongitude = startCityP->fLongitude;
  1242.         gPath[gPathCount].fEndLatitude = endCityP->fLatitude;
  1243.         gPath[gPathCount].fEndLongitude = endCityP->fLongitude;
  1244.         gPath[gPathCount].fTripStartTime = 0;
  1245.         gPath[gPathCount].fTripDuration = 0;
  1246.         
  1247.         gPathCount++;
  1248.     };
  1249.     return true;
  1250. };
  1251.  
  1252. Boolean InitializeCitiesList() {
  1253.     Handle    cityDataH = GetResource ('CTY#', -4064);
  1254.     CityRecordPtr        cityP = nil, lastCity = nil;
  1255.     Ptr                    r;
  1256.     int                    index, count;
  1257.  
  1258.     if (!cityDataH)
  1259.         return false;
  1260.  
  1261.     HLock(cityDataH);
  1262.     count = * (short *) *cityDataH;
  1263.     r = *cityDataH + sizeof(short);
  1264.     
  1265.     for (index = 1; index <= count; ++index) {
  1266.         CityRecordPtr cityP = (CityRecordPtr) NewPtrClear(sizeof(*cityP));
  1267.  
  1268.         if (cityP) {
  1269.             CityResourceFormatPtr resP = (CityResourceFormatPtr) r;
  1270.             
  1271.             BlockMove((Ptr) resP->fCityName, (Ptr) cityP->fCityName, resP->fCityName[0]+1);
  1272.             cityP->fLongitude = Frac2X(resP->fLongitude);    
  1273.             cityP->fLatitude = Frac2X(resP->fLatitude);    
  1274.             cityP->fGMTOffset = resP->fGMTOffset;
  1275.             cityP->fNext = nil;
  1276.             
  1277.             r += resP->fRecordSize;
  1278.  
  1279.             if (lastCity) {
  1280.                 lastCity->fNext = cityP;
  1281.             } else {
  1282.                 gCitiesRecordList = cityP;
  1283.             };
  1284.             lastCity = cityP;
  1285.         } else {
  1286.             break;
  1287.         };
  1288.     };
  1289.     
  1290.     ReleaseResource (cityDataH);
  1291.  
  1292.     //    Fake some city shit.
  1293.     {    unsigned long now;
  1294.     
  1295.         #if 0
  1296.         GetDateTime (&now);
  1297.         AddCityToPath(FindCity("\pDetroit"), FindCity("\pDallas"), now, now + 20);
  1298.         AddCityToPath(FindCity("\pDallas"), FindCity("\pCupertino"), now + 30, now + 40);
  1299.         #endif
  1300.     };
  1301.  
  1302.     ReadPathListInFromResources();
  1303.  
  1304.     CreateTrafficMenu ();
  1305.     
  1306.     return true;
  1307. };
  1308.  
  1309. Boolean InitializeWorldMap() {
  1310.     if (gWorldMapPicH == nil) {
  1311.         gWorldMapPicH = (PicHandle) GetResource ('PICT', 129);
  1312.         
  1313.         if (gWorldMapPicH) {
  1314.             gWorldMapPicSize.h = (**gWorldMapPicH).picFrame.right - (**gWorldMapPicH).picFrame.left;
  1315.             gWorldMapPicSize.v = (**gWorldMapPicH).picFrame.bottom - (**gWorldMapPicH).picFrame.top;
  1316.         };
  1317.     };
  1318.         
  1319.     return true;
  1320. };
  1321.  
  1322. Boolean ShiftKeyDown() { return false; };
  1323.  
  1324. Boolean BlinkCity (WindowPtr window, CityRecordPtr cityP) {
  1325.     Rect    goofyRect;
  1326.     long    xPos, yPos;
  1327.     
  1328.     if (ShiftKeyDown())  {
  1329.         DebugStr (cityP->fCityName);
  1330.     };
  1331.     
  1332.     SetPort(gOurWindow);
  1333.  
  1334.     GetXandYPositionOverMap(cityP->fLatitude, cityP->fLongitude,  &xPos, &yPos);
  1335.  
  1336.     if (IsPointInVisibleAreaOfMap(goofyRect.left, goofyRect.top)) {
  1337.         goofyRect.top = yPos;  goofyRect.bottom = goofyRect.top + 1;
  1338.         goofyRect.left = xPos; goofyRect.right = goofyRect.left + 1;
  1339.  
  1340.         InsetRect (&goofyRect, -1, -1);
  1341.  
  1342.         FillOval (&goofyRect, &qd.white);
  1343.         PenPat(&qd.gray);
  1344.         FrameOval(&goofyRect);
  1345.     };
  1346.     
  1347.     return true;
  1348. };
  1349.  
  1350. Boolean BlinkAllCities (WindowPtr window) {
  1351.     CityRecordPtr            cityP;
  1352.     
  1353.     cityP = gCitiesRecordList;
  1354.     
  1355.     while (cityP) {
  1356.         BlinkCity (window, cityP);
  1357.         cityP = cityP->fNext;
  1358.     };
  1359.  
  1360.     return true;
  1361. };
  1362.  
  1363.  
  1364.  
  1365. long CalculateHowFarItIsToTheHorizonInMiles(long altitudeInMiles) {
  1366.     extended alpha;
  1367.     long distanceToHorizon;
  1368.     
  1369.     alpha = acos(((extended) kEarthsRadiusInMiles) / 
  1370.                         ((extended) (kEarthsRadiusInMiles + altitudeInMiles)));
  1371.     
  1372.     distanceToHorizon = kEarthsRadiusInMiles * alpha;
  1373.     
  1374.     return distanceToHorizon;
  1375.  
  1376. }
  1377.  
  1378.  
  1379.  
  1380.  
  1381.  
  1382.  
  1383.  
  1384.  
  1385.  
  1386. Boolean ReadPathListInFromResources () {
  1387.     int    index, count;
  1388.     Handle    resH;
  1389.     
  1390.     gPathCount= 0;
  1391.     count = CountResources ('PATH');
  1392.     
  1393.     for (index = 1 ; index <= count; ++index) {
  1394.         resH = GetIndResource ('PATH', index);
  1395.         
  1396.         if ((resH) && (*resH)) {
  1397.             Ptr    p = *resH;
  1398.             CityRecordPtr    cityP;
  1399.             
  1400.             BlockMove (p, gPath[gPathCount].fStartingCity, *p + 1);
  1401.             cityP = FindCity (gPath[gPathCount].fStartingCity);
  1402.             if (cityP) {
  1403.                 gPath[gPathCount].fStartLatitude = cityP->fLatitude;
  1404.                 gPath[gPathCount].fStartLongitude = cityP->fLongitude;
  1405.             };
  1406.             p += (*p + 1);
  1407.  
  1408.             BlockMove (p, gPath[gPathCount].fEndingCity, *p + 1);
  1409.             cityP = FindCity (gPath[gPathCount].fEndingCity);
  1410.             if (cityP) {
  1411.                 gPath[gPathCount].fEndLatitude = cityP->fLatitude;
  1412.                 gPath[gPathCount].fEndLongitude = cityP->fLongitude;
  1413.             };
  1414.             p += (*p + 1); if (!(((int) p) & 1)) p++;
  1415.             
  1416.             gPath[gPathCount].fTripDuration = * (long *) p;
  1417.             gPath[gPathCount].fTripStartTime = 0;
  1418.             gPathCount++;
  1419.         };
  1420.     };
  1421. };
  1422.  
  1423.  
  1424. void CreateTrafficMenu () {
  1425.     int    index;
  1426.     Str255 s;
  1427.     MenuHandle menuH = GetMenu(mLight);
  1428.     
  1429.     for (index = 0; index < gPathCount; ++index) {
  1430.         PLstrcpy(&s, gPath[index].fStartingCity);
  1431.         PLstrcat(&s, "\p » ");
  1432.         PLstrcat(&s, gPath[index].fEndingCity);
  1433.         PLstrcat(&s, "\p/");
  1434.         if (index < 10)
  1435.             s[++s[0]] =  index + 1 + '0';
  1436.         AppendMenu (menuH, s);
  1437.         EnableItem (menuH, index+1);
  1438.     };
  1439. };
  1440.